//
//  OrderViewController.m
//  HuaLang
//
//  Created by iking on 2017/11/20.
//  Copyright © 2017年 iking. All rights reserved.
//

#import "TuiKuanViewController.h"
#import "SGSegmentedControl.h"
#import "OrderTableViewCell.h"
#import "OrderDetailViewController.h"
#import "ShouHouViewController.h"
#import "PingJiaViewController.h"
#import "TuiKuanDetailViewController.h"

@interface TuiKuanViewController ()<UITableViewDelegate,UITableViewDataSource,SGSegmentedControlStaticDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SGSegmentedControlStatic *topSView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation TuiKuanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    [self loadBaseTitleLable:@"商品售后"];
    [self setUpUI];
    
    self.selectIndex = 0;
    self.currentPage = 1;
    self.pageSize = 20;
    // 请求数据
    [self getGoodsListData];
}
#pragma mark - 订单列表
- (void)getGoodsListData
{
    NSString *status;
    status = [NSString stringWithFormat:@"%ld",(long)self.selectIndex];
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/aftersale.ashx?action=list&companyid=%@&code=%@&timestamp=%@&pagesize=%@&pageindex=1&status=%@&from=mobile",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],[NSString stringWithFormat:@"%ld",(long)self.pageSize],status] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        self.dataArray = [NSMutableArray array];
        self.currentPage = 1;
        if ([responseObject[@"status"] intValue] == 1) {
            NSArray *array = responseObject[@"RepairsList"];
            for (NSDictionary *dic in array) {
                [self.dataArray addObject:dic];
            }
        }
        NSInteger i = [responseObject[@"RepairsCount"] intValue]/self.pageSize;
        NSInteger j = [responseObject[@"RepairsCount"] intValue]%self.pageSize;
        NSInteger n = 0;
        if (j > 0) {
            n = i+1;
        } else {
            n = i;
        }
        if (n<2) {
            self.tableView.mj_footer.hidden = YES;
        } else {
            self.tableView.mj_footer.hidden = NO;
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)getGoodsListDataMore
{
    self.currentPage++;
    NSString *status;
    status = [NSString stringWithFormat:@"%ld",(long)self.selectIndex];
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/aftersale.ashx?action=list&companyid=%@&code=%@&timestamp=%@&pagesize=%@&pageindex=%@&status=%@&from=mobile",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],[NSString stringWithFormat:@"%ld",(long)self.pageSize],[NSString stringWithFormat:@"%ld",(long)self.currentPage],status] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        if ([responseObject[@"status"] intValue] == 1) {
            
            NSInteger i = [responseObject[@"RepairsCount"] intValue]/self.pageSize;
            NSInteger j = [responseObject[@"RepairsCount"] intValue]%self.pageSize;
            NSInteger n = 0;
            if (j > 0) {
                n = i+1;
            } else {
                n = i;
            }
            if (self.currentPage > n) {
                self.currentPage--;
                self.tableView.mj_footer.hidden = YES;
            } else {
                self.tableView.mj_footer.hidden = NO;
                NSArray *array = responseObject[@"RepairsList"];
                for (NSDictionary *dic in array) {
                    [self.dataArray addObject:dic];
                }
                [self.tableView reloadData];
            }
        } else {
            self.currentPage--;
            self.tableView.mj_footer.hidden = YES;
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)setUpUI
{
    [self addSegment];
    
    [self.view addSubview:self.tableView];
}
#pragma mark - 分段选择
- (void)addSegment
{
    // 采购订单
    NSArray *title_arr = @[@"待审核",@"已驳回",@"待邮寄",@"已收货",@"处理中",@"已完成"];
    self.topSView = [SGSegmentedControlStatic segmentedControlWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, rateHeight(90)) delegate:self childVcTitle:title_arr indicatorIsFull:NO];
    _topSView.backgroundColor = UIColorWhite;
    // 必须实现的方法
    [self.topSView SG_setUpSegmentedControlType:^(SGSegmentedControlStaticType *segmentedControlStaticType, NSArray *__autoreleasing *nomalImageArr, NSArray *__autoreleasing *selectedImageArr) {
    }];
    [self.view addSubview:_topSView];
    _topSView.selectedIndex = 0;
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight+rateHeight(90), kScreenWidth, rateHeight(10))];
    line.backgroundColor = tableViewBgColor;
    [self.view addSubview:line];
}
#pragma mark - segment delegate
- (void)SGSegmentedControlStatic:(SGSegmentedControlStatic *)segmentedControlStatic didSelectTitleAtIndex:(NSInteger)index {
    if (segmentedControlStatic == _topSView) {
        self.selectIndex = index;
        NSLog(@"index - - %ld", (long)index);
        [self getGoodsListData];
    }
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderTableViewCell *cell = [[OrderTableViewCell alloc] init];
    // 赋值
    if (_dataArray.count != 0) {
        NSDictionary *dic = _dataArray[indexPath.section];
        [cell.goodsImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",dic[@"CartImg"]]] placeholderImage:UIImageNamed(@"placeholder")];
        cell.goodsTitleLB.text = dic[@"CommodityName"];
        cell.describeLB.text = dic[@"CommodityProperty"];
        cell.priceLB.hidden = YES;
        cell.numLB.hidden = YES;
        
    }
    cell.selectionStyle = NO;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateHeight(180);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return rateHeight(70);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return rateHeight(80);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = UIColorWhite;
    
    UILabel *label = [UILabel labelWithText:@"订单编号：" textColor:UIColorFromRGB(0x3b3b3b) fontSize:13];
    [label sizeToFit];
    [bgV addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgV);
        make.left.equalTo(bgV).offset(rateWidth(30));
    }];
    UILabel *label1 = [UILabel labelWithText:@"" textColor:UIColorFromRGB(0xf55555) fontSize:13];
    [label1 sizeToFit];
    [bgV addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgV);
        make.right.equalTo(bgV).offset(-rateWidth(30));
    }];
    
    // 赋值
    if (_dataArray.count != 0) {
        NSDictionary *dic = _dataArray[section];
        label.text = [NSString stringWithFormat:@"订单编号：%@",dic[@"ordersId"]];
        if ([dic[@"repairsStatus"] intValue] == 0) {
            label1.text = @"待审核";
        } else if ([dic[@"repairsStatus"] intValue] == 1) {
            label1.text = @"已驳回";
        } else if ([dic[@"repairsStatus"] intValue] == 2) {
            label1.text = @"待邮寄";
        } else if ([dic[@"repairsStatus"] intValue] == 3) {
            label1.text = @"已收货";
        } else if ([dic[@"repairsStatus"] intValue] == 4) {
            label1.text = @"处理中";
        } else if ([dic[@"repairsStatus"] intValue] == 5) {
            label1.text = @"已完成";
        }
        
    }
    return bgV;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = tableViewBgColor;
    UIView *whiteV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateHeight(70))];
    whiteV.backgroundColor = UIColorWhite;
    [bgV addSubview:whiteV];
    UILabel *label = [UILabel labelWithText:@"" textColor:UIColorFromRGB(0x3b3b3b) fontSize:13];
    [label sizeToFit];
    [whiteV addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(whiteV);
        make.left.equalTo(whiteV).offset(rateWidth(30));
    }];
    // 赋值
    if (_dataArray.count != 0) {
        NSDictionary *dic = _dataArray[section];
        label.text = dic[@"repairsCreatTime"];
    }
    
    return bgV;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArray.count != 0) {
        NSDictionary *dic = _dataArray[indexPath.section];
        TuiKuanDetailViewController *tuiKuanDetailVC = [[TuiKuanDetailViewController alloc] init];
        tuiKuanDetailVC.cartid = dic[@"CartId"];
        tuiKuanDetailVC.commodityid = dic[@"Contentid"];
        tuiKuanDetailVC.orderId = dic[@"ordersId"];
        [self.navigationController pushViewController:tuiKuanDetailVC animated:YES];
    }
    
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight+rateHeight(90)+rateHeight(10), kScreenWidth, kScreenHeight-SafeAreaTopHeight-rateHeight(90)-rateHeight(10)) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = tableViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf getGoodsListData];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [weakSelf getGoodsListDataMore];
        }];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
